<?php

namespace utils\workerman\http;

use think\Exception;
use think\response\File;

class ResponseFile extends File
{
    /**
     * Mine type map.
     * @var array
     */
    protected static ?array $_mimeTypeMap = null;
    
    /**
     * 初始化
     * @access protected
     * @param mixed $data 输出数据
     * @param int $code 状态码
     * @throws \Exception
     */
    protected function init($data = '', int $code = 200): void
    {
        $this->data($data);
        $this->code = $code;
        $this->output($data);
    }
    
    /**
     * 处理数据
     * @access protected
     * @param  mixed $data 要处理的数据
     * @return mixed
     * @throws \Exception
     */
    protected function output($data): mixed
    {
        if (!$this->isContent && !is_file($data)) {
            throw new Exception('file not exists:' . $data);
        }
        
        while (ob_get_level() > 0) {
            ob_end_clean();
        }
        
        $this->getMimeType($data);
        
        return $this->isContent ? $data : file_get_contents($data);
    }
    
    /**
     * 获取文件类型信息
     * @access public
     * @param  string $filename 文件名
     * @return string
     */
    protected function getMimeType(string $filename): string
    {
        // $this->header['Server'] = 'workerman';
        // $this->header['Connection'] = 'keep-alive';
        
        $file_info = \pathinfo($filename);
        $extension = $file_info['extension'] ?? '';
        $base_name = $file_info['basename'] ?? 'unknown';
        
        if (isset(self::$_mimeTypeMap[$extension])) {
            $this->header['Content-Type'] = self::$_mimeTypeMap[$extension];
        } else {
            $this->header['Content-Type'] = 'application/octet-stream';
        }
        
        
        if (!isset($this->header['Content-Disposition']) && !isset(self::$_mimeTypeMap[$extension])) {
            $this->header['Content-Disposition'] = 'attachment; filename=' . $base_name;
        }
        
        if (!isset($this->header['Last-Modified'])) {
            if ($mtime = \filemtime($filename)) {
                $this->header['Last-Modified'] = \gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
            }
        }
        
        $this->header['Pragma']                    = 'public';
        $this->header['Cache-control']             = 'max-age=' . $this->expire;
        // $this->header['Content-Length']            = $size;
        $this->header['Content-Transfer-Encoding'] = 'binary';
        $this->header['Expires']                   = gmdate("D, d M Y H:i:s", time() + $this->expire) . ' GMT';
        
        return $this->header['Content-Type'];
        
    }
    
    
    /**
     * Init mime map.
     *
     * @return void
     */
    public static function initMimeTypeMap()
    {
        $mime_file = __DIR__ . '/mime.types';
        $items = \file($mime_file, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);
        foreach ($items as $content) {
            if (\preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match)) {
                $mime_type       = $match[1];
                $extension_var   = $match[2];
                $extension_array = \explode(' ', \substr($extension_var, 0, -1));
                foreach ($extension_array as $file_extension) {
                    static::$_mimeTypeMap[$file_extension] = $mime_type;
                }
            }
        }
    }
}
ResponseFile::initMimeTypeMap();